# -*- coding: utf-8 -*-
# https://blog.csdn.net/weixin_52040868
# 公众号：测个der
# 微信：qing_an_an
import os

from PyQt5.QtCore import QUrl

from new_func.messages import Content
from PyQt5.QtGui import QIcon
from qfluentwidgets import FluentWindow, RoundMenu, Action, NavigationItemPosition
from qfluentwidgets import FluentIcon as FIF
from new_func.ui_unpack import UnpackWidget
from new_func.ui_filter import FilterWidget
from new_func.ui_average import AverageWidget
from new_func.ui_separate import SeparateWidget
from new_func.ui_document import DocumentWidget
from new_func.ui_excel import ExcelWidget
from new_func.tools import Tool
from new_func.ui_thread import Worker
from PyQt5.QtWidgets import QApplication


class Window(FluentWindow):
    """ 主界面 """

    def __init__(self):
        super().__init__()
        self.setMicaEffectEnabled(False)  # 规避win11带来的边框黑化
        self.tool = Tool()
        self.Separate = SeparateWidget('separate_ui', self)
        self.Unpack = UnpackWidget('unpack_ui', self)
        self.Average = AverageWidget('average_ui', self)
        self.Filter = FilterWidget('filter_ui', self)
        self.Document = DocumentWidget("document_ui", self)
        self.Excel = ExcelWidget("excel_ui", self)

        print(r"""
        📢By: 清安：https://gitee.com/qinganan_admin/pyqt5-comprehensive-tool

                                                   .__
         ___.__. ____  __ __   __ __  ____ |  |__ _____  ______ ______ ___.__.
        <   |  |/  _ \|  |  \ |  |  \/    \|  |  \\__  \ \____ \\____ <   |  |
         \___  (  <_> )  |  / |  |  /   |  \   Y  \/ __ \|  |_> >  |_> >___  |
         / ____|\____/|____/  |____/|___|  /___|  (____  /   __/|   __// ____|
         \/                              \/     \/     \/|__|   |__|   \/
        #                    __  __
        #       _ _        /_@)_@) \          /^^\ /^\ /^^\_
        #    _/oo \____/~''. . .  '~\       /'\''  ~ ''~~' -'\_
        #   / '.'. ~.~.~.       .'    ~ |     /'\~~..''''.'' ''  ~\_
        #  ('_'_'_'_'_'_'_'_  ' :   '     \_/' '.''  . '.   .''  '.  ~\_
        #  ~V~V~V~V  \   ~\  '' '~  '   '' ~   `   ~  ''   ~\_
        #    /\~/\~/\~/\~/|/  '   ''  _   ' ~ ''  '    ~  '' __  '  ..  \_
        # <-- --- ---.---.--/'   ''   /'  '\_ '' ': ~ ;;''    ' /''; \ ;'''''' '' ~\ _
        #    \~ '. . : .:: ~. :.  /_'''_'' \_' :'''_ : _ ''/''_' '_ \:_ '''' #''..\/\/\/~/\~ ''~~~~~O
        # ~~ \-~ `---~~~---- \(_)(_)(_)/ ~ ~~' ~\(_)(_)(_)\_~_~_~_~_~/˜¤¹

                """)

        """初始化界面"""
        self.success_fired = False
        self.warn_fired = False
        self.error_fired = False

        self.init_navigation()
        self.add_loading_ui()
        self.click_prompt_signal()
        self.window_signals()
        self.init_window()

    def window_signals(self):
        """信号出发子线程启动"""
        self.Unpack.excelDataUnpack.clicked.connect(lambda: self.unpack_thread(self.Unpack.excel_unpack_click))
        self.Unpack.btn_get_all_data.clicked.connect(lambda: self.unpack_thread(self.Unpack.csv_unpack_click))
        self.Average.average_sum_btn.clicked.connect(lambda: self.average_thread(self.Average.average_value))
        # info跳电
        self.Separate.btn_info_jump.clicked.connect(lambda: self.separate_thread(btn_text=self.Separate.btn_info_jump,
                                                                                 widget=self.Separate.get_info_jump))
        # bat跳电
        self.Separate.btn_bat_jump.clicked.connect(lambda: self.separate_thread(btn_text=self.Separate.btn_bat_jump,
                                                                                widget=self.Separate.get_bat_jump))
        # 时长
        self.Separate.appoint_time.clicked.connect(lambda: self.separate_thread(self.Separate.appoint_time,
                                                                                self.Separate.get_info_batterry_time))
        # 指定时长
        self.Separate.specify_time.clicked.connect(
            lambda: self.separate_specify_thread(self.Separate.specify_calculation))
        # csv及excel单项数据
        self.Filter.loding_chart.clicked.connect(
            lambda: self.filter_thread(self.Filter.line_chart))
        # excel专项数据
        self.Excel.loding_chart.clicked.connect(
            lambda: self.excel_thread(self.Excel.line_chart))

    def loading_chart(self, widget):
        """加载图表"""
        widget.chart_view.load(QUrl.fromLocalFile(os.path.abspath("lineChart.html")))  # 加载生成的图形
        # widget.chart_view.setHtml(getattr(self.tool, 'html'))  # 加载生成的图形

    def run_worker(self, widget):
        self.worker = Worker(widget)
        self.worker.start()  # 启动任务
        self.worker.stop()

    def excel_thread(self, widget):
        """excel数据专项处理"""
        if self.Excel.loding_line.text():
            self.Excel.chart.connect(lambda: self.loading_chart(self.Excel))
            self.run_worker(widget)
            self.warn_fired = False
        else:
            self.tool.show_warn(self)

    def filter_thread(self, widget):
        """filter线程，绘制html"""
        if self.Filter.loding_line.text():
            self.Filter.chart.connect(lambda: self.loading_chart(self.Filter))
            self.run_worker(widget)
            self.warn_fired = False
        else:
            self.tool.show_warn(self)

    def separate_thread(self, btn_text, widget):
        """单独计算ui线程"""
        self.Separate.error.connect(lambda: self.fire_signal('se_error'))
        text = btn_text.text()
        if text not in ['充放电时长', 'info跳电', 'bat跳电']:
            self.run_worker(widget)
            self.error_fired = False
        else:
            self.tool.show_error(self, "获取信息错误", f"当前获取的是{text}， 检查参数信息")

    def separate_specify_thread(self, widget):
        """单独计算-指定电量-ui线程"""
        self.Separate.warn.connect(lambda: self.fire_signal('se_warn'))
        if self.tool.get_text(self.Separate.separate_line):
            self.run_worker(widget)
            self.warn_fired = False
        else:
            self.tool.show_warn(self)

    def average_thread(self, widget):
        """计算平均值ui线程"""
        self.Average.error.connect(lambda: self.fire_signal('av_error'))
        if self.Average.average_filepath_line.text():
            self.run_worker(widget)
        else:
            self.tool.show_warn(self)
        self.error_fired = False

    def unpack_thread(self, widget):
        """解析文件ui线程"""
        self.Unpack.success.connect(lambda: self.fire_signal('success'))
        self.Unpack.warn.connect(lambda: self.fire_signal('warn'))
        self.Unpack.error.connect(lambda: self.fire_signal('error'))
        if self.Unpack.excelPath.text() or self.Unpack.line_filename.text():
            self.run_worker(widget)
        else:
            self.tool.show_warn(self)
        self.success_fired = False
        self.warn_fired = False
        self.error_fired = False

    def fire_signal(self, signal_type):
        """判断弹窗，3.10+版本新增case"""
        match signal_type:
            case 'success' if not self.success_fired:
                self.success_fired = True
                self.tool.show_success(self)
            case 'warn' if not self.warn_fired:
                self.warn_fired = True
                self.tool.show_warn(self)
            case 'error' if not self.error_fired:
                self.error_fired = True
                self.tool.show_error(self, "数据有误", "日志信息不完整 请使用CSV进行专项处理")
            case 'av_error' if not self.error_fired:
                self.error_fired = True
                self.tool.show_error(self, "❗️类型错误", "当前的值既不是 int 也不是float")
            case 'se_error' if not self.error_fired:
                self.error_fired = True
                self.tool.show_error(self, "参数有误", " 检查当前参数/数据是否符合或丢失")
            case 'se_warn' if not self.warn_fired:
                self.warn_fired = True
                self.tool.show_warn(self)
            case _:
                pass
        # if signal_type == 'success' and not self.success_fired:
        #     self.success_fired = True
        #     self.tool.show_success(self)
        # elif signal_type == 'warn' and not self.warn_fired:
        #     self.warn_fired = True
        #     self.tool.show_warn(self)
        # elif signal_type == 'error' and not self.error_fired:
        #     self.error_fired = True
        #     self.tool.show_error(self, "数据有误", "日志信息不完整 请使用CSV进行专项处理")
        # elif signal_type == 'av_error' and not self.error_fired:
        #     self.error_fired = True
        #     self.tool.show_error(self, "❗️类型错误", "当前的值既不是 int 也不是float")
        # elif signal_type == 'se_error' and not self.error_fired:
        #     self.error_fired = True
        #     self.tool.show_error(self, "参数有误", " 检查当前参数/数据是否符合或丢失")
        # elif signal_type == 'se_warn' and not self.warn_fired:
        #     self.warn_fired = True
        #     self.tool.show_warn(self)

    def init_navigation(self):
        """添加UI"""
        self.addSubInterface(self.Unpack, FIF.MARKET, '数据解析')
        self.addSubInterface(self.Average, FIF.PENCIL_INK, '计算平局值')
        self.addSubInterface(self.Separate, FIF.DEVELOPER_TOOLS, '数据独立显示')
        self.addSubInterface(self.Filter, FIF.PIE_SINGLE, '数据图表')
        self.addSubInterface(self.Excel, FIF.ERASE_TOOL, 'EXCEL专属')
        self.addSubInterface(
            self.Document, FIF.DOCUMENT, self.tr('简介'), NavigationItemPosition.BOTTOM)

    def click_prompt_signal(self):
        """提示信号"""
        self.tool.prompt(self.Unpack.unpack_prompt, Content.UNPACK_TITLE.value, Content.UNPACK_CONTENT.value)
        self.tool.prompt(self.Average.average_prompt, Content.AVERAGE_TITLE.value, Content.AVERAGE_CONTENT.value)
        self.tool.prompt(self.Separate.separate_info, Content.SEPARATE_TITLE.value, Content.SEPARATE_CONTENT.value)

    def add_loading_ui(self):
        """二次处理Ui"""
        self.Separate.btn_bat_jump.setFlyout(
            self.create_filter_menu(self.Separate.btn_bat_jump, ["充电", "放电"]))
        self.Separate.btn_info_jump.setFlyout(
            self.create_filter_menu(self.Separate.btn_info_jump, ["充电", "放电"]))
        self.Separate.appoint_time.setFlyout(
            self.create_filter_menu(self.Separate.appoint_time, ["充电", "放电"]))

    def create_filter_menu(self, button, filter_select):
        """创建filter菜单"""
        menu = RoundMenu(parent=self)
        for value in filter_select:
            menu.addActions([
                Action(FIF.SEND, self.tr(value), triggered=lambda c, value=value, b=button: b.setText(self.tr(value)))
                # Action(FIF.SEND, self.tr('CSV'), triggered=lambda c, b=button: b.setText(self.tr('CSV'))),
            ])
        return menu

    def init_window(self):
        self.resize(1100, 800)
        self.setWindowIcon(QIcon(':/icons/images/icon.ico'))
        self.setWindowTitle('数据处理工具')

        desktop = QApplication.desktop().availableGeometry()
        w, h = desktop.width(), desktop.height()
        self.move(w // 2 - self.width() // 2, h // 2 - self.height() // 2)


if __name__ == '__main__':
    app = QApplication([])
    window = Window()
    window.show()
    app.exec_()

# 打包指令  Pyinstaller -D -w -i resources\images\icon.ico --name="ADP"  run.py
